package com.app.aipass.fragment.my.exchangepoints;

/**
 * @author: woking
 * @date: 2021/6/9
 * @description：
 */

import android.app.Application;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;

import com.app.aipass.app.AppApplication;
import com.app.aipass.data.DemoRepository;
import com.app.aipass.entity.ExchangeCoinEntity;
import com.app.aipass.entity.ExchangeHomeEntity;
import com.app.aipass.entity.Message;
import com.app.aipass.entity.PointEntity;
import com.app.aipass.entity.ShopTokenEntity;
import com.app.aipass.entity.UserEntity;
import com.app.aipass.fragment.my.task.TaskFragment;
import com.app.aipass.http.response.ApiException;
import com.app.aipass.utils.ShareUtil;
import com.app.aipass.utils.TextUtil;
import com.app.aipass.utils.ToastUtils;

import java.util.HashMap;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.observers.DisposableObserver;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.RxBus;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.http.BaseResponse;
import me.goldze.mvvmhabit.http.ResponseThrowable;
import me.goldze.mvvmhabit.utils.RxUtils;
import okhttp3.ResponseBody;
import retrofit2.Response;

public class ExchangePointsViewModel extends BaseViewModel<DemoRepository>
{
    //使用Observable
    public SingleLiveEvent<Boolean> requestCameraPermissions = new SingleLiveEvent<>();
    //使用LiveData
    public SingleLiveEvent<ExchangeHomeEntity> mExchangeHomeEntity = new SingleLiveEvent<>();
    public SingleLiveEvent<ExchangeCoinEntity> mExchangeCoinEntity = new SingleLiveEvent<>();
    public SingleLiveEvent<PointEntity> mPointEntity = new SingleLiveEvent<>();

    public SingleLiveEvent<Boolean> mExchangeFinish = new SingleLiveEvent<>();
    public ExchangePointsViewModel(@NonNull Application application, DemoRepository repository) {
        super(application, repository);
    }
    public void exchangeCoin()
    {
        model.exchangeCoin()
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(this)//请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        showDialog("正在请求...");
                    }
                })
                .subscribe(new DisposableObserver<BaseResponse<ExchangeCoinEntity>>() {
                    @Override
                    public void onNext(BaseResponse<ExchangeCoinEntity> response) {
                        Log.e("TAG","============exchangeCoin=====onNext========");

                        if(null != response && null != response.getData())
                        {
                            mExchangeCoinEntity.postValue(response.getData());
                        }else {
                            ToastUtils.showShort(response.getMessage());
                        }
                    }
                    @Override
                    public void onError(Throwable throwable) {
                        Log.e("TAG","============exchangeCoin=====onError========"+throwable.getMessage());
                        dismissDialog();
                        if (throwable instanceof ResponseThrowable) {
                            ToastUtils.showShort("不在兑换时间内");
                        }
                    }
                    @Override
                    public void onComplete() {
                        dismissDialog();
                        Log.e("TAG","============exchangeCoin=====onComplete========");
                    }
                });
    }
    public void exchangeHome()
    {
        model.exchangeHome()
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(this)//请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        showDialog("正在请求...");
                    }
                })
                .subscribe(new DisposableObserver<BaseResponse<ExchangeHomeEntity>>() {
                    @Override
                    public void onNext(BaseResponse<ExchangeHomeEntity> response) {
                        Log.e("TAG","============exchangeHome=====onNext========");

                        if(null != response && null != response.getData())
                        {
                            mExchangeHomeEntity.postValue(response.getData());
                        }
                    }
                    @Override
                    public void onError(Throwable throwable) {
                        Log.e("TAG","============exchangeHome=====onError========");
                        dismissDialog();
                        if (throwable instanceof ResponseThrowable) {
                            ToastUtils.showShort(((ResponseThrowable) throwable).message);
                        }
                    }
                    @Override
                    public void onComplete() {
                        dismissDialog();
                        Log.e("TAG","============exchangeHome=====onComplete========");
                    }
                });
    }
    public void pointWallet() {
        exchangeCoin();
        model.pointWallet()
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(this)//请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        showDialog("正在请求...");
                    }
                })
                .subscribe(new DisposableObserver<BaseResponse<PointEntity>>() {
                    @Override
                    public void onNext(BaseResponse<PointEntity> response) {
                        Log.e("TAG","============pointWallet=====onNext========");
                        if(null != response && null != response.getData())
                        {
                            mPointEntity.postValue(response.getData());
                        }
                    }
                    @Override
                    public void onError(Throwable throwable) {
                        Log.e("TAG","============pointWallet=====onError========"+throwable.getMessage());
                        dismissDialog();
//                        if (throwable instanceof ResponseThrowable) {
//                            ToastUtils.showShort(((ResponseThrowable) throwable).message);
//                            String msg = ApiException.getShowmessage(((ResponseThrowable) throwable).errorBody);
//                            ToastUtils.showShort(msg);
//                        }
//                        exchangeCoin();
                    }
                    @Override
                    public void onComplete() {
                        dismissDialog();
                        Log.e("TAG","============pointWallet=====onComplete========");
//                        exchangeCoin();
                    }
                });
    }
    public void exchange(HashMap<String, Object> map)
    {
        model.exchange(map)
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(this)//请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        showDialog("正在请求...");
                    }
                })
                .subscribe(new DisposableObserver<Response<Void>>() {
                    @Override
                    public void onNext(Response<Void> response) {
                        Log.e("TAG","=====123=======exchange=====onNext=00=======");
                        try {
                            if(response != null) {
                                if (response.code() >= 200 && response.code() < 300) {
                                    ToastUtils.showShort("已兑换");
                                    ExchangePointsFragment.isRefreshExchange = true;
                                    RxBus.getDefault().post(new Message("RefreshExchange", ""));
                                    if (map.containsKey("exchange_level")) {
                                        int level = (int) map.get("exchange_level");
                                        if (AppApplication.ad_exchange_level != level) {
                                            baseUser();
                                        }
                                    }
                                } else {
//                                    dismissDialog();
                                    ToastUtils.showShortSafe(ApiException.getShowmessage(response.errorBody().string()));
                                }
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    @Override
                    public void onError(Throwable throwable) {
                        Log.e("TAG","=====123===000====exchange=====onError========");
                        dismissDialog();
//                        String errorMsg = throwable.getMessage();
//                        if (throwable instanceof ResponseThrowable) {
////                            ToastUtils.showShort(((ResponseThrowable) throwable).message);
//                            String msg = ApiException.getShowmessage(((ResponseThrowable) throwable).errorBody);
//                            if(!TextUtil.isEmpty(msg) && msg.equals("成功"))
//                            {
//                                if(!TextUtil.isEmpty(errorMsg) && errorMsg.contains("time out"))
//                                {
//
//                                }
//                                else
//                                {
//                                    int code = ((ResponseThrowable) throwable).code;
//                                    if(code > 199 && code < 300)
//                                    {
//                                        ToastUtils.showShort("已兑换");
//                        ExchangePointsFragment.isRefreshExchange = true;
//                                        RxBus.getDefault().post(new Message("RefreshExchange",""));
//                                        if(map.containsKey("exchange_level"))
//                                        {
//                                            int level = (int)map.get("exchange_level");
//                                            if( AppApplication.ad_exchange_level != level)
//                                            {
//                                                baseUser();
//                                            }
//                                        }
//                                    }
//                                }
//                            }
//                            else
//                            {
//                                ToastUtils.showShort(msg);
//                            }
//                        }
                    }
                    @Override
                    public void onComplete() {
                        dismissDialog();
                        Log.e("TAG","======123======exchange=====onComplete========");
//                        ToastUtils.showShort("已兑换");
//                        ExchangePointsFragment.isRefreshExchange = true;
//                        RxBus.getDefault().post(new Message("RefreshExchange",""));
//                        if(map.containsKey("exchange_level"))
//                        {
//                            int level = (int)map.get("exchange_level");
//                            if( AppApplication.ad_exchange_level != level)
//                            {
//                                baseUser();
//                            }
//                        }
                    }
                });
    }
    public void baseUser() {
        Log.e("TAG","==========baseUser=============");
        model.baseUser()
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(this)//请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        showDialog("正在请求...");
                    }
                })
                .subscribe(new DisposableObserver<BaseResponse<UserEntity>>() {
                    @Override
                    public void onNext(BaseResponse<UserEntity> response) {
                        Log.e("TAG","================baseUser===onNext====");
                        if(null != response && null != response.getData())
                        {
                            ((AppApplication)AppApplication.getInstance()).setUserEntity(response.getData());
                            if( AppApplication.ad_exchange_level != response.getData().ad_exchange_level)
                            {
                                AppApplication.ad_exchange_level = response.getData().ad_exchange_level;
                                mExchangeFinish.postValue(true);
                            }

                        }
                    }
                    @Override
                    public void onError(Throwable throwable) {
                        Log.e("TAG","================baseUser===onError===="+throwable.getMessage());
                        dismissDialog();
                    }
                    @Override
                    public void onComplete() {
                        Log.e("TAG","================baseUser===onComplete====");
                        dismissDialog();
                    }
                });
    }
    public void pointExchange(HashMap<String, Object> map)
    {
        model.pointExchangeCsc(map)
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(this)//请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        showDialog("正在请求...");
                    }
                })
                .subscribe(new DisposableObserver<ResponseBody>() {
                    @Override
                    public void onNext(ResponseBody response) {
                        Log.e("TAG","============pointExchangeCsc=====onNext========");

//                        if(null != response && null != response.getData())
//                        {
//                            mExchangeHomeEntity.postValue(response.getData());
//                        }
                    }
                    @Override
                    public void onError(Throwable throwable) {
                        String errorMsg = throwable.getMessage();
//                        Log.e("TAG","========222====pointExchangeCsc=====onError========"+errorMsg);
                        dismissDialog();
                        if (throwable instanceof ResponseThrowable) {
//                            ToastUtils.showShort(((ResponseThrowable) throwable).message);
                            String msg = ApiException.getShowmessage(((ResponseThrowable) throwable).errorBody);
                            Log.e("TAG",ApiException.getInstance().getCode()+"============pointExchangeCsc=====onError=====111==="+((ResponseThrowable) throwable).code);
                            if(!TextUtil.isEmpty(msg) && msg.equals("成功"))
                            {
                                if(!TextUtil.isEmpty(errorMsg) && errorMsg.contains("time out"))
                                {

                                }
                                else
                                {
                                    int code = ((ResponseThrowable) throwable).code;
                                    if(code > 199 && code < 300)
                                    {
                                        ToastUtils.showShort("已兑换");
                                        ExchangePointsFragment.isRefreshExchange = true;
                                        RxBus.getDefault().post(new Message("RefreshExchange",""));
                                        if(map.containsKey("exchange_level"))
                                        {
                                            int level = (int)map.get("exchange_level");
                                            if( AppApplication.ad_exchange_level != level)
                                            {
                                                baseUser();
                                            }
                                        }
                                    }
                                }
                            }
                            else
                            {
                                ToastUtils.showShort(msg);
                            }
                        }
                    }
                    @Override
                    public void onComplete() {
                        dismissDialog();
                        Log.e("TAG","============pointExchangeCsc=====onComplete========");
                        ToastUtils.showShort("已兑换");
                        ExchangePointsFragment.isRefreshExchange = true;
                        RxBus.getDefault().post(new Message("RefreshExchange",""));
                        if(map.containsKey("exchange_level"))
                        {
                            int level = (int)map.get("exchange_level");
                            if( AppApplication.ad_exchange_level != level)
                            {
                                baseUser();
                            }
                        }
                    }
                });
    }

    public void getShopToken()
    {
        model.getShopToken()
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(this)//请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
//                        showDialog("正在请求...");
                    }
                })
                .subscribe(new DisposableObserver<BaseResponse<ShopTokenEntity>>() {
                    @Override
                    public void onNext(BaseResponse<ShopTokenEntity> response) {
                        Log.e("TAG","============getShopToken=====onNext========");
//                        //请求成功
//                        if (response.getCode() == 200) {
//                            mShopTokenEntity.postValue(response.getData());
//                        } else {
//                            //code错误时也可以定义Observable回调到View层去处理
//                            ToastUtils.showShort("数据错误");
//                        }
                    }
                    @Override
                    public void onError(Throwable throwable) {
                        Log.e("TAG","============getShopToken=====onError========");
                        if (throwable instanceof ResponseThrowable) {
                            ToastUtils.showShort(((ResponseThrowable) throwable).message);
                        }
                    }
                    @Override
                    public void onComplete() {
                        Log.e("TAG","============getShopToken=====onComplete========");
                    }
                });
    }

    public void taskClick(View v)//任务包
    {
        Log.e("TAG","============taskClick=============");
        startContainerActivity(TaskFragment.class.getCanonicalName());
    }

    //兑换积分
    public BindingCommand exchange_pointsClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
//            startContainerActivity(MultiRecycleViewFragment.class.getCanonicalName());
            Log.e("TAG","============taskClick=============");
        }
    });
    //活跃指数
    public BindingCommand activeClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
//            startActivity(TabBarActivity.class);
        }
    });
    //安全中心
    public BindingCommand safeClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
//            startActivity(ViewPagerActivity.class);
        }
    });


    public void getZTXShopToken()
    {
        Log.e("TAG","============getZTXShopToken=============");
        if(((AppApplication)AppApplication.getInstance()).getUserEntity() == null)
        {
            return;
        }
        model.getZTXShopToken(((AppApplication)AppApplication.getInstance()).getUserEntity().mobile)
//        model.getCSCToken(token)
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(this)//请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
//                        showDialog("正在请求...");
                    }
                })
                .subscribe(new DisposableObserver<BaseResponse<ShopTokenEntity>>() {
                    @Override
                    public void onNext(BaseResponse<ShopTokenEntity> response) {
                        Log.e("TAG","============getZTXShopToken==========onNext===");
                        if(null != response && null != response.getData())
                        {
                            ShareUtil.getInstance().save(ShareUtil.ZTX_SHOP_TOKEN , response.getData().token_type+" " + response.getData().access_token);


                        }
                    }
                    @Override
                    public void onError(Throwable throwable) {
                        Log.e("TAG","============getZTXShopToken======onError======="+throwable.getMessage());
//                        if (throwable instanceof ResponseThrowable) {
//                            ToastUtils.showShortSafe(((ResponseThrowable) throwable).message);
//                        }
                    }
                    @Override
                    public void onComplete() {
                        Log.e("TAG","============getZTXShopToken=======onComplete======");
                        pointWallet();
                    }
                });
    }
}